package com.service.socket.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.dao.enums.KlineTypeEnum;
import com.service.dao.mapper.Kline10080Mapper;
import com.service.dao.model.Kline10080;
import com.service.dao.model.Kline1440;
import com.service.dao.po.KlineVo;
import com.service.socket.service.Kline10080Service;
import com.service.socket.service.KlineService;
import com.service.socket.service.KlineServiceFactory;
import com.service.utility.modelmapper.ModelMapperUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;


@Service()
//@DS("slave_1")
public class Kline10080ServiceImpl extends ServiceImpl<Kline10080Mapper, Kline10080> implements Kline10080Service, KlineService, InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        KlineServiceFactory.register(KlineTypeEnum.line_10080, this);
    }

    @Override
    public KlineVo getByOpenTimeAndSymbol(Long openTime, String symbol) {
        Kline10080 kline = getOne(new QueryWrapper<Kline10080>().lambda()
                .eq(Kline10080::getTimeOpen, openTime)
                .eq(Kline10080::getSymbol, symbol).last("limit 1"));
        return ObjectUtils.isEmpty(kline) ? null : ModelMapperUtil.map(kline, KlineVo.class);
    }

    @Override
    public KlineVo getLastOneBySymbol(String symbol) {
        Kline10080 kline = getOne(new QueryWrapper<Kline10080>().lambda()
                .eq(Kline10080::getSymbol, symbol).orderByDesc(Kline10080::getTimeOpen).last("limit 1"));
        return ObjectUtils.isEmpty(kline) ? null : ModelMapperUtil.map(kline, KlineVo.class);
    }

    @Override
    public void updateKline(KlineVo klineVo) {
        saveOrUpdate(ModelMapperUtil.map(klineVo, Kline10080.class));
    }

    @Override
    public List<KlineVo> listBySymbolAndLimit(String symbol, Long openTime, Integer limit) {
        return list(new QueryWrapper<Kline10080>().lambda()
                .eq(Kline10080::getSymbol, symbol)
                .le(Kline10080::getTimeOpen, openTime)
                .orderByDesc(Kline10080::getTimeOpen)
                .last("limit " + limit))
                .stream().map(item -> ModelMapperUtil.map(item, KlineVo.class))
                .collect(Collectors.toList());
    }

}
